package plug_in_javafx_dt.projectnature;

import java.net.URI;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;

public class JFXProjectSupport {

	private static final String[] PATH_STRUCTURE = {"source","test", "resouces"}; 
	
	public static IProject createProject(String projectName, URI url) {
		IProject project;
		try {

		     project = createJFXProject(projectName, url);
			 addJFXNature(project);
			 addJFXProjectStructure(project);

		} catch (Exception e) {
			e.printStackTrace();
			project = null;
		}
		
		return project;

	}

	private static IProject createJFXProject(String projectName, URI url)
			throws CoreException {
		IProject newProject = ResourcesPlugin.getWorkspace().getRoot()
				.getProject(projectName);

		if (!newProject.exists()) {
			URI projectLocation = url;
			IProjectDescription description = newProject.getWorkspace().newProjectDescription(projectName);

			if(projectLocation != null && ResourcesPlugin.getWorkspace().getRoot().getLocationURI().equals(projectLocation) ){
				projectLocation = null;
			}
			
			description.setLocationURI(projectLocation);

			newProject.create(description, null);
			if (!newProject.isOpen()) {
				newProject.open(null);
			}

		}
		return newProject;

	}

	private static void addJFXNature(IProject project) throws CoreException {

		if (!project.hasNature(JFXNature.NATURE_ID)) {
			IProjectDescription description = project.getDescription();

			String[] previousNatures = description.getNatureIds();
			String[] newNatures = new String[previousNatures.length + 2];
			System.arraycopy(previousNatures, 0, newNatures, 0,
					previousNatures.length);
			newNatures[previousNatures.length] = JFXNature.NATURE_ID;
			newNatures[previousNatures.length+1] = "org.eclipse.jdt.core.javanature";

			description.setNatureIds(newNatures);

			project.setDescription(description, null);
		}

	}
	
	private static void createFolder(IFolder folder) throws CoreException {
		IContainer parent = folder.getParent();
		if(parent instanceof IFolder){
			createFolder((IFolder)parent);
		}
		if(!folder.exists()){
			folder.create(false, true, null);
		}
		
	}
	
	private static void addJFXProjectStructure(IProject project) throws CoreException {
		for(String path : PATH_STRUCTURE){
			IFolder folder = project.getFolder(path);
			createFolder(folder);
		}
		
	}
}

